import { defineStore } from "pinia";
import {
  JxtechUser,
  getAccessToken,
  getRefreshToken,
  LoginUser,
  rsaencode,
  aesencode,
  JxtechToken,
  setAccessToken,
  setRefreshToken
} from "@whjxtech/jxtech-component";
import { useSysconfigrStore } from "@/stores/modules/sysconfig";

export type Encodeface = {
  account: string;
  password: string;
};

/**
 * 脚手架user对象
 */
export type JxtechWebStarterUser = JxtechUser & {
  routeBreadcrumbMappingMap: any;
  menuPagePoint: any;
};

export const useUserStore = defineStore({
  id: "jxtech-user",
  state: (): JxtechWebStarterUser => ({
    accountNonExpired: false,
    accountNonLocked: false,
    adminApp: null,
    credentialsNonExpired: false,
    deptCode: null,
    deptId: null,
    deptName: null,
    deptTreePath: null,
    enabled: false,
    orgId: null,
    orgName: null,
    orgTreePath: null,
    roles: [],
    stationId: null,
    stationName: null,
    subOrgCode: null,
    subOrgId: null,
    subOrgName: null,
    subOrgTreePath: null,
    telenantAdminOrg: false,
    userAccount: null,
    userAttributes: null,
    userDeptId: null,
    userFullName: null,
    userId: null,
    userImageUrl: null,
    userLevel: null,
    userType: null,

    userDeptList: [],
    token: getAccessToken() || null,
    refreshToken: getRefreshToken() || null,
    menus: [],
    //这两个后期可能放到别的状态里面去
    routeMappingMap: {},
    routeBreadcrumbMappingMap: {},
    firstMenusIndex: "",
    menuPagePoint: {}
  }),
  getters: {},
  actions: {
    /**登录 */
    login(loginUser: LoginUser) {
      const sysConfigState = useSysconfigrStore();
      let encodeObject: Encodeface = { account: "", password: "" };
      // rsa加密
      if (sysConfigState.encriptType === "rsa") {
        encodeObject = rsaencode(loginUser.account as string, loginUser.password as string, sysConfigState.rsaPublicKey);
      } else if (sysConfigState.encriptType === "aes") {
        // aes加密
        encodeObject.account = aesencode(
          loginUser.account as string,
          sysConfigState.aeskey as string,
          sysConfigState.aesiv as string
        );
        encodeObject.password = aesencode(
          loginUser.password as string,
          sysConfigState.aeskey as string,
          sysConfigState.aesiv as string
        );
      }
      if (loginUser.actionType && loginUser.actionType === "depart") {
        encodeObject.account = loginUser.account as string;
        encodeObject.password = loginUser.password as string;
      }

      return new Promise((resolve, reject) => {
        login(encodeObject)
          .then(res => {
            this.loginSuccessAfter(res.data);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /**登录成功后处理 */
    loginSuccessAfter(responseData: JxtechToken) {
      //存入store
      this.setToken(responseData);
      //设置toekn
      setAccessToken(responseData.access_token);
      //设置刷新token
      setRefreshToken(responseData.refresh_token);
      /* ---------------------------------------- zhuliangyu 2024/4/3 优化token失效问题 start  ---------------------------------------- */
      //存入失效时间
      const expireTime = Number(responseData._t) + responseData.expires_in * 1000;
      localStorage.setItem("expireTime", String(expireTime));
      /* ---------------------------------------- zhuliangyu 2024/4/3 优化token失效问题 end  ---------------------------------------- */
    },
    /**设置store token */
    setToken(responseToken: JxtechToken) {
      this.token = responseToken.access_token;
      this.refreshToken = responseToken.refresh_token;
    }
  }
});
